

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
# 设置中文字体
plt.rcParams.update({
    'font.size': 16,          # 全局字体大小
    'axes.titlesize': 18,     # 标题字体大小
    'axes.labelsize': 14,     # 坐标轴标签字体大小
    'xtick.labelsize': 14,    # x轴刻度字体
    'ytick.labelsize': 14,    # y轴刻度字体
    'legend.fontsize': 14     # 图例字体
})
# 初始化设置
plt.rcParams['font.sans-serif'] = ['KaiTi']  # 中文字体
plt.rcParams['mathtext.fontset'] = 'stix'     # 数学字体
plt.rcParams['axes.unicode_minus'] = False

# 定义目标函数
def f(x, y):
    return x**2 + y**2

# 定义约束函数
def g(x, y):
    return x + y - 1

# 生成数据点
x = np.linspace(-2, 3, 100)
y = np.linspace(-2, 3, 100)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

# 创建3D图形
fig = plt.figure(figsize=(18, 8))

# 绘制3D曲面图
ax1 = fig.add_subplot(121, projection='3d')
surf = ax1.plot_surface(X, Y, Z, cmap=cm.coolwarm, alpha=0.8)
fig.colorbar(surf, ax=ax1, shrink=0.5, aspect=5)

# 绘制约束平面
Z_constraint = np.zeros_like(X)
for i in range(len(x)):
    for j in range(len(y)):
        if g(x[i], y[j]) <= 0:
            Z_constraint[i, j] = f(x[i], y[j])
ax1.plot_surface(X, Y, Z_constraint, color='green', alpha=0.3)

ax1.xaxis.label.set_fontsize(18)
ax1.yaxis.label.set_fontsize(18)
ax1.zaxis.label.set_fontsize(18)
ax1.tick_params(axis='z', labelsize=14)

ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_zlabel('f(x,y)')
ax1.set_title('目标函数$f(x,y) = x^2 + y^2$及其约束函数$g(x, y) = x + y - 1 \leq 0$')

# 绘制等高线图
ax2 = fig.add_subplot(122)
contour = ax2.contour(X, Y, Z, 20, cmap=cm.coolwarm)
fig.colorbar(contour, ax=ax2, shrink=0.8, aspect=5)

# 绘制约束区域
constraint = ax2.contourf(X, Y, g(X, Y), levels=[-10, 0], colors='green', alpha=0.3)

# 标记最小值点
critical_point = (0, 0)
ax2.plot(critical_point[0], critical_point[1], 'ro', markersize=8)
ax2.annotate(f'最小值点 ({critical_point[0]}, {critical_point[1]})',
             xy=(critical_point[0], critical_point[1]),
             xytext=(critical_point[0]+0.3, critical_point[1]+0.3),
             arrowprops=dict(facecolor='black', shrink=0.05))

ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_title('函数等高线图及约束区域')
ax2.grid(True)

plt.tight_layout()
plt.show()



